import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_name_and_nick_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_sliver_delegate/common_sliver_delegate.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/common_person_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/company/company_person_list_view_model.dart';
import 'package:e_reception_flutter/ui/company/manager/select_person_page.dart';
import 'package:e_reception_flutter/ui/person_detail/person_detail_page.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_label_utils.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../app_main.dart';

///企业主页 管理员列表
class ManagerListPage extends StatefulWidget {
  static const String ROUTER = 'ManagerListPage';

  ///跳转方法
  static Future<Map> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult<Map>(
      context,
      ManagerListPage(),
      routeName: ManagerListPage.ROUTER,
    );
  }

  @override
  State<StatefulWidget> createState() {
    return ManagerListPageState();
  }
}

class ManagerListPageState
    extends BasePagerState<CommonPersonBean, ManagerListPage>
    with VgPlaceHolderStatusMixin<CommonPersonBean, ManagerListPage> {
  CommonPersonListViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel =
        CommonPersonListViewModel(this, CommonPersonListViewModel.TYPE_MANAGER);
    _viewModel?.refresh();
    VgEventBus.global.on<RefreshCompanyDetailPageEvent>().listen((event) {
      print("管理员列表收到：${event.toString()}");
      _viewModel?.refresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        backgroundColor:
            ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: Container(
          child: Column(
            children: <Widget>[
              _toTopBarWidget(),
              Expanded(
                child: NestedScrollView(
                  headerSliverBuilder: (context, bool) {
                    return [
                      SliverPersistentHeader(
                        delegate: CommonSliverPersistentHeaderDelegate(
                          minHeight: 50,
                          maxHeight: 50,
                          child: Container(
                            color: ThemeRepository.getInstance()
                                .getCardBgColor_21263C(),
                            padding: EdgeInsets.symmetric(vertical: 10),
                            child: CommonSearchBarWidget(
                              hintText: "搜索",
                              onChanged: (keyword) {
                                _viewModel.keyword = keyword;
                                _viewModel.refresh();
                              },
                              onSubmitted: (keyword) {
                                _viewModel.keyword = keyword;
                                _viewModel.refresh();
                              },
                            ),
                          ),
                        ),
                      ),
                    ];
                  },
                  body: _toPullRefreshWidget(),
                ),
              ),
            ],
          ),
        ),
      ),
      navigationBarColor:
          ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  ///topbar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "管理员",
      titleFontSize: 17,
      isShowBack: true,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      isHideRightWidget: !AppOverallDistinguish.comefromAiOrWeStudy(),
      rightWidget: Visibility(
        visible: VgRoleUtils.isSuperAdmin(
            UserRepository.getInstance().getCurrentRoleId()),
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () async {
            bool result = await SelectUserPage.navigatorPush(context);
            if (result != null && result) {
              _viewModel.refresh();
            }
          },
          child: Container(
            height: 44,
            alignment: Alignment.center,
            child: Text(
              "+添加",
              style: TextStyle(color: Color(0xFF1890FF), fontSize: 14),
              textAlign: TextAlign.left,
            ),
          ),
        ),
      ),
    );
  }

  Widget _toPullRefreshWidget() {
    return VgPullRefreshWidget.bind(
        state: this,
        viewModel: _viewModel,
        enablePullDown: true,
        child: ListView.separated(
            itemCount: data?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            itemBuilder: (BuildContext context, int index) {
              if (data == null || data.length <= index) {
                return Container();
              }
              return _listItem(data[index]);
            },
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 0,
              );
            }));
  }

  @override
  void finishRefresh({Duration duration}) {
    super.finishRefresh(duration: duration);
    loading(false);
  }

  @override
  void finishLoadMore() {
    super.finishLoadMore();
    loading(false);
  }

  Widget _listItem(CommonPersonBean data) {
    return Container(
      child: _toMainRowWidget(context, data),
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      height: 60,
      padding: EdgeInsets.symmetric(vertical: 11, horizontal: 15),
    );
  }

  Widget _toMainRowWidget(BuildContext context, CommonPersonBean itemBean) {
    return GestureDetector(
        onTap: () {
          PersonDetailPage.navigatorPush(context, itemBean.fuid, fid:itemBean?.fid);
        },
        behavior: HitTestBehavior.opaque,
        child: Row(
          children: <Widget>[
            ClipRRect(
                borderRadius: BorderRadius.circular(4),
                child: Container(
                  width: 36,
                  height: 36,
                  child: VgCacheNetWorkImage(
                    showOriginEmptyStr(itemBean?.putpicurl) ??
                        showOriginEmptyStr(itemBean?.napicurl ?? "") ??
                        '',
                    fit: BoxFit.cover,
                    imageQualityType: ImageQualityType.middleDown,
                    defaultErrorType: ImageErrorType.head,
                    defaultPlaceType: ImagePlaceType.head,
                  ),
                )),
            SizedBox(
              width: 10,
            ),
            Container(
              height: 40,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  //第一栏
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      CommonNameAndNickWidget(
                        name: itemBean?.name,
                        nick: itemBean?.nick,
                      ),
                      VgLabelUtils.getRoleLabel(itemBean?.roleid) ??
                          Container(),
                      _toPhoneWidget(itemBean),
                    ],
                  ),
                  //第二栏 昨天23:34登录APP
                  _loginTimeWidget(itemBean)
                ],
              ),
            ),
            Expanded(
              child: _toColumnWidget(itemBean),
            ),
          ],
        ));
  }

  Widget _toPhoneWidget(CommonPersonBean itemBean) {
    return Offstage(
      offstage: itemBean.phone == null || itemBean.phone.isEmpty,
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _call(itemBean?.phone);
        },
        child: Container(
          width: 16,
          height: 16,
          margin: const EdgeInsets.only(left: 4, right: 10),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(2),
              color: ThemeRepository.getInstance()
                  .getPrimaryColor_1890FF()
                  .withOpacity(0.1)),
          child: Icon(
            Icons.phone,
            size: 10,
            color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          ),
        ),
      ),
    );
  }

  void _call(String phone) async {
    if (StringUtils.isEmpty(phone)) {
      return;
    }
    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      VgToastUtils.toast(AppMain.context, "手机号不正确");
      return;
    }
    if (await canLaunch("tel:" + phone)) {
      await launch("tel:" + phone);
    } else {
      throw 'Could not launch $phone';
    }
  }

  ///当前是否为超管权限
  bool isSuperAdminRole() {
    return UserRepository.getInstance().userData.comUser.roleid == '99';
  }

  /// 管理1台终端
  /// 北方研发部/121人
  _toColumnWidget(CommonPersonBean itemBean) {
    return Visibility(
      visible: itemBean.roleid != ROLE_SUPER_ADMIN,
      child: Container(
        height: 40,
        child: DefaultTextStyle(
          style: TextStyle(fontFamily: "PingFang", height: 1),
          child: SizedBox(
            height: 36,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Container(
                  alignment: Alignment.bottomRight,
                  height: 16,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: getTerminalShowWidgets(itemBean),
                    mainAxisAlignment: MainAxisAlignment.end,
                  ),
                ),
                Spacer(),
                SizedBox(
                  child: Row(
                    children: getDepartmentStrWidgets(itemBean),
                    mainAxisAlignment: MainAxisAlignment.end,
                  ),
                ),
                SizedBox(height: 1,)
              ],
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> getTerminalShowWidgets(CommonPersonBean itemBean) {
    List<Widget> widgets;
    //管理1台终端
    if (itemBean.hsnCnt > 0) {
      widgets = [
        Text('管理', style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR)),
        Text('${itemBean.hsnCnt}',
            style: TextStyle(
                fontSize: 10,
                height: 1,
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF())),
        Text('台显示屏', style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR)),
      ];
    } else {
      widgets = [
        Text(
          '未分配显示屏',
          style: TextStyle(
              fontSize: 10,
              color:
                  itemBean.hsnCnt > 0 ? Color(0xffd0e0f7) : Color(0xff5e687c),
              height: 1.1),
        ),
      ];
    }
    return widgets;
  }

  // ///分类名称·编号
  // String _getGroupAndIdStr(String groupName, String number) {
  //   if (StringUtils.isEmpty(groupName) && StringUtils.isEmpty(number)) {
  //     return null;
  //   }
  //   if (StringUtils.isNotEmpty(groupName) && StringUtils.isEmpty(number)) {
  //     return groupName;
  //   }
  //   if (StringUtils.isEmpty(groupName) && StringUtils.isNotEmpty(number)) {
  //     return number;
  //   }
  //   return groupName + "·" + number;
  // }

  ///4/20 12:22李岁红邀请    邀请两个字用红色
  _loginTimeWidget(CommonPersonBean itemBean) {
    if (itemBean == null) {
      return SizedBox();
    }
    if (itemBean.lasttime == null) {
      return Text.rich(TextSpan(children: [
        TextSpan(
            text: itemBean.createdate == null
                ? ''
                : "${VgDateTimeUtils.getFormatTimeStr(itemBean.createdate)}",
            style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
        TextSpan(
            text:
                StringUtils.isEmpty(itemBean.uname) ? '' : "${itemBean.uname}",
            style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
        TextSpan(
            text: StringUtils.isEmpty(itemBean.uname) ? '' : '邀请',
            style: TextStyle(fontSize: 12, color: Color(0xfff95355))),
        // TextSpan(
        //     text:
        //     StringUtils.isEmpty(itemBean.uname) ? '' : "·",
        //     style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
        // TextSpan(
        //     text: '未登录APP',
        //     style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR))
      ]));
    } else {
      //激活的显示上次登录时间
      return Text(VgDateTimeUtils.getFormatTimeStr(itemBean.lasttime) + "登录APP",
          style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR));
    }
  }

  /// 部门
  ///北方研发部/121人
  ///3个部门/121人
  ///未分配部门
  List<Widget> getDepartmentStrWidgets(CommonPersonBean itemBean) {
    if (itemBean == null) {
      return [SizedBox()];
    }
    if (UserRepository.getInstance().userData.companyInfo.isCompanyLike()) {
      if ((itemBean.departmentCnt ?? 0) > 0) {
        if (itemBean.departmentCnt > 1) {
          return [
            Text('${itemBean.departmentCnt}',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('个部门/',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
            Text('${itemBean.personCnt ?? 0}',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('人',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
          ];
        } else {
          return [
            Text(
                "${VgStringUtils.subStringAndAppendSymbol((itemBean.department ?? ''), 7, symbol: "...")}",
                // Text('${itemBean.department ?? ''}',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
            Text('/',
                style: TextStyle(fontSize: 10, color: VgColors.INPUT_BG_COLOR)),
            Text('${itemBean.personCnt ?? 0}',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('人',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
          ];
        }
      } else {
        return [
          Text('未分配管理部门',
              style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
        ];
      }
    } else {
      if ((itemBean.classCnt ?? 0) > 0) {
        if (itemBean.classCnt > 1) {
          return [
            Text('${itemBean.classCnt}',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('个班级/',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
            Text('${itemBean.personCnt ?? 0}',
                style: TextStyle(
                    fontSize: 12,
                    height: 1.2,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('人',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
          ];
        } else {
          return [
            Text(
                "${VgStringUtils.subStringAndAppendSymbol((itemBean.classname ?? '暂无班级名'), 7, symbol: "...")}",
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
            Text('/',
                style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
            Text('${itemBean.personCnt ?? 0}',
                style: TextStyle(
                    fontSize: 12,
                    color: ThemeRepository.getInstance()
                        .getPrimaryColor_1890FF())),
            Text('人',
                style: TextStyle(
                  fontSize: 12,
                  color: VgColors.INPUT_BG_COLOR,
                )),
          ];
        }
      } else {
        return [
          Text('未分配管理班级',
              style: TextStyle(fontSize: 12, color: VgColors.INPUT_BG_COLOR)),
        ];
      }
    }
  }
}
